import { getNodes } from '@/api/node'

const state = {
  loading: false,
  nodeList: [],
  localnode: '', // 本地节点
  nodeNameList: [], // 所有 node 名称的集合
  choseNode: {} // 选择 node 的数据
}

const mutations = {
  SET_NODE_LOADING(state, loading) {
    state.loading = loading
  },
  SET_NODE_LIST(state, data) {
    state.nodeList = data
  },
  SET_LOCALNODE(state, data) {
    state.localnode = data
  },
  SET_NODE_NAME_LIST(state, data) {
    state.nodeNameList = data
  },
  SET_CHOSE_NODE(state, data) {
    state.choseNode = data
  }
}

const actions = {
  // 获取节点列表数据
  fetchNodeData({ commit }) {
    commit('SET_NODE_LOADING', true)

    return getNodes().then((res) => {
      commit('SET_NODE_LOADING', false)
      if (res.data.action) {
        const nodeList = JSON.parse(JSON.stringify(res.data.data))
        const nodeNameList = []

        // 处理节点数据
        nodeList.forEach(function(node) {
          nodeNameList.push(node.id)

          // 处理节点状态
          if (node.standby) {
            node.status = 'Running/Standby'
          } else if (!node.health) {
            node.status = 'Not Running'
          } else {
            node.status = 'Running'
          }
        })

        commit('SET_NODE_LIST', nodeList)
        commit('SET_LOCALNODE', res.data.localnode || '')
        commit('SET_NODE_NAME_LIST', nodeNameList)

        return res.data
      } else {
        return Promise.reject(res.data.error)
      }
    }).catch((error) => {
      commit('SET_NODE_LOADING', false)
      throw error
    })
  },

  // 设置选中的节点
  changeChoseNode({ commit }, node) {
    commit('SET_CHOSE_NODE', node)
  }
}

const getters = {
  nodeLoading: state => state.loading,
  nodeList: state => state.nodeList,
  localnode: state => state.localnode,
  nodeNameList: state => state.nodeNameList,
  choseNode: state => state.choseNode
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
